//
// Created by 张易生 on 2022/1/12.
//

#ifndef ZYSPLAYER_ZYSAUDIOPLAYER_H
#define ZYSPLAYER_ZYSAUDIOPLAYER_H

#include "AndroidLog.h"
#include "ZYSPlayStatus.h"
#include "ZYSQueue.h"
#include "ZYSCallJava.h"
#include "SoundTouch.h"

extern "C"
{
#include "libavcodec/avcodec.h"
#include <libswresample/swresample.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
};

using namespace soundtouch;

class ZYSAudioPlayer {

public:
    int streamIndex = -1;
    AVCodecContext *avCodecContext = nullptr;
    AVCodecParameters *codecpar = nullptr;
    ZYSQueue *queue = nullptr;

    ZYSPlayStatus *playStatus = nullptr;
    uint8_t *buffer = nullptr;
    int data_size = 0;
    int sample_rate = 0;


    pthread_t thread_play;
    AVPacket *avPacket = NULL;
    AVFrame *avFrame = NULL;
    int ret = 0;

    // 引擎接口
    SLObjectItf engineObject = NULL;
    SLEngineItf engineEngine = NULL;

    //混音器
    SLObjectItf outputMixObject = NULL;
    SLEnvironmentalReverbItf outputMixEnvironmentalReverb = NULL;
    SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;
    //缓冲器队列接口
    SLAndroidSimpleBufferQueueItf pcmBufferQueue = NULL;
    //pcm
    SLObjectItf pcmPlayerObject = NULL;
    //播放暂停的接口
    SLPlayItf pcmPlayerPlay = NULL;
    //声道的接口
    SLMuteSoloItf playerMute = NULL;
    //当前声道：立体声
    int mute = 2;
    //声音大小接口
    SLVolumeItf playerVolume = NULL;

    //总时长
    int duration = 0;
    //时间单位         总时间/帧数   单位时间     *   时间戳= pts  * 总时间/帧数
    AVRational time_base;
    //当前时间
    double now_time = 0;//当前frame时间

    double clock = 0;//当前播放的时间    准确时间

    double last_time = 0; //上一次调用时间

    //倍速
    float speed = 1.0f;

    //音调
    float pitch = 1.0f;

    int buffer_number;

    //是否整理完波
    bool soundTouchFinish= true;

    ZYSCallJava *callJava = NULL;

    SoundTouch *soundTouch;

    //SoundTouch需要的数据，入参出参对象
    uint8_t *out_buffer = NULL;

    //新的缓冲区, SoundTouch整理完放入，给到opensles进行播放
    SAMPLETYPE  *sampleBuffer = NULL;
    //新波的数量
    int newPcmNum = 0;

public:
    ZYSAudioPlayer(ZYSPlayStatus *playstatus, int sample_rate, ZYSCallJava *callJava);

    ~ZYSAudioPlayer();

    //开始播放
    void play();

    //暂停
    void pause();

    //恢复
    void resume();
    void stop();

    void initOpenSLES();

    int getCurrentSampleRateForOpensles(int sample_rate);

    int resampleAudio(void **pVoid);

    int getSoundTouchSampleData();

    //声道
    void setMute(int mute);

    //声音大小
    void setVolume(int percent);

    //倍速
    void setSpeed(float speed);

    //变音调
    void setPitch(float pitch);

    void release();

    void playPCM();
};


#endif //ZYSPLAYER_ZYSAUDIOPLAYER_H
